#!/bin/bash

PROGNAME="${BASH_SOURCE[0]}"
HERE="$(cd "$(dirname "$PROGNAME")" &>/dev/null && pwd)"
ROOT=$(cd $HERE/../.. && pwd)
READIES=$ROOT/deps/readies
. $READIES/shibumi/defs

(( VERBOSE > 1 )) && { set -x; PS4='$LINENO: '; }

if [[ $1 == --help || $1 == help ]]; then
	cat <<-END
		Invoke QA Automation tests

		[ARGVARS...] run [--help|help]

		Argument variables:
 		QA_AUTOMATION_TOKEN=token     QA automation (Opereto) token
		TEST=name                     Name of .json parameters file
		MODULE_VERSION=ver            Module version to test. Default: master
		NOP=1                         Do not execute automation command
		VERBOSE=N                     Set verbosity level (N=1,2)
		QUICK=1                       Only test one RS version

		Other configuration:
		RS_VERSIONS file includes Redis Enterprive versions for release tests.

	END
	exit 0
fi

export RS_MODULE=RedisGraph
export RS_MODULE_FILE_PREFIX=redisgraph

if [[ -z $QA_AUTOMATION_TOKEN && $NOP != 1 ]]; then
	echo "Variable QA_AUTOMATION_TOKEN is undefined." >&2
	exit 1
fi

export TEST=${TEST:-release}
if [[ ! -f $HERE/$TEST.json ]]; then
	echo "Invalid TEST name: $TEST" >&2
	exit 1
fi

run_test() {
	export RS_VERSION=$1

	if [[ -z $MODULE_VERSION ]]; then
		export MODULE_VERSION=master
	else
		export MODULE_VERSION=$(echo "$MODULE_VERSION" | sed  's/^v\(.*\)/\1/')
	fi

	results() {
		echo "$JSON" | jq "$1" | cut -d\" -f2
	}

	cd $HERE

	json_in=$(mktemp /tmp/$TEST.json.XXXX)
	$READIES/bin/xtx -e RS_MODULE -e RS_MODULE_FILE_PREFIX -e MODULE_VERSION -e RS_VERSION $TEST.json > $json_in
	(( VERBOSE >= 1 )) && cat $json_in

	if [[ $NOP == 1 ]]; then
		echo "Testing RS $RS_VERSION"
		return 0
	fi
	
  	OPERETO3_URL="opereto.qa.redislabs.com"
	JSON=$(curl -sk \
   		-X POST -H "Content-Type: application/json" \
   		-H "Authorization: Bearer $QA_AUTOMATION_TOKEN" \
   		-d @$json_in \
   		https://$OPERETO3_URL/processes 2>&1)
	rc=$?
	rm $json_in
	status=$(results .status)
	if [[ $rc == 0 && $status == success ]]; then
		id=$(results .data[0])
		echo "Tests running on $MODULE_VERSION for RS $RS_VERSION"
		echo "Results: https://$OPERETO3_URL/ui#dashboard/flow/$id"
		return 0
	else
		err=$(results .message)
		echo "Failed to run tests on $MODULE_VERSION for RS $RS_VERSION: $err"
		return 1
	fi
}

rc=0
if [[ $QUICK == 1 ]]; then
	RS_VERSIONS=$(cat $HERE/RS_VERSIONS | head -1)
else
	RS_VERSIONS=$(cat $HERE/RS_VERSIONS)
fi
for RS_VERSION in $RS_VERSIONS; do
	run_test $RS_VERSION
	[[ $? != 0 && $rc == 0 ]] && rc=$?
done
exit $rc
